import low from 'lowdb'
import LocalStorage from 'lowdb/adapters/LocalStorage'
import globalInterface from '@/common/global'
import { cloneDeep } from 'lodash'
import { paramsType, dbStore } from './types/util.db'

const adapter = new LocalStorage(`${process.env.VUE_APP_PROJECT_NAME}-${process.env.VUE_APP_VERSION}`)
const db = low(adapter)

export const dbStoreName: dbStore = {
  user: 'user',
  sys: 'sys'
}

db.defaults({ user: {}, sys: {} }).write()

export default db

export function calculatePath (obj: globalInterface.IObject) {
  // 拿到想要操作的路径
  const currentPath = `${obj.dbName}.${obj.path}` ? `${obj.dbName}.${obj.path}` : `${obj.dbName}`

  // 获取这个路径下的值
  const value = db.get(currentPath).value()

  // 如果这个值不存在，那么就走set,进行初始化,如果存在那么就返回这个路径
  if (value === 'undefined') {
    db.set(currentPath, '').write()
  }
  return currentPath
}

export function dbSet ({ dbName = 'sys', path = '', value }: paramsType) {
  db.set(calculatePath({ dbName, path }), value).write()
}

export function dbGet ({ dbName = 'sys', path = '' }): any {
  // return new Promise(resolve => {
  //   resolve(cloneDeep(db.get(calculatePath({ dbName, path })).value()))
  // })
  return cloneDeep(db.get(calculatePath({ dbName, path })).value())
}
